const CryptoJS = require("crypto-js")
const { aesKey } = require("./config/config.json");

class Handler {
    static AESEncrypt(word) {
        const cryptoKey = CryptoJS.enc.Utf8.parse(aesKey); // 加密的key
        const iv = CryptoJS.enc.Utf8.parse(aesKey) // 密码偏移量

        let srcs = CryptoJS.enc.Utf8.parse(word);
        var encrypted = CryptoJS.AES.encrypt(srcs, cryptoKey, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.ZeroPadding
        });
        return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    }

    static AESDecrypt(word) {
        const cryptoKey = CryptoJS.enc.Utf8.parse(aesKey) // 加密的key
        const iv = CryptoJS.enc.Utf8.parse(aesKey) // 密码偏移量

        let base64 = CryptoJS.enc.Base64.parse(word);
        let src = CryptoJS.enc.Base64.stringify(base64);

        let decrypt = CryptoJS.AES.decrypt(src, cryptoKey, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.ZeroPadding
        });

        let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        return decryptedStr.toString();
    }

    static userToToken(user) {
        const text = `${user},${new Date()}`;
        return this.AESEncrypt(text);
    }

    static tokenToUser(token) {
        const word = this.AESDecrypt(token)
        return word.split(',');
    }

    static getIdentityId(name) {
        const word = `${Date.now()},${name}`;
        return this.AESEncrypt(word);
    }

    static getActorId(word) {
        const actor = this.AESDecrypt(word).split(',');
        const delay = Date.now() - actor[0];
        if (delay > 10000) return undefined;
        return actor[1];
    }
}

module.exports = Handler;